package com.startx.core.tools;

import java.lang.reflect.Field;
import java.util.Properties;
import java.util.Set;

import org.apache.log4j.Logger;

/**
 * 配置工具类
 * @author minghu.zhang
 */
public class ConfigTool {
	
	private static final Logger Log = Logger.getLogger(ConfigTool.class);
	
	/**
	 * 配置对象
	 */
	private Object config;
	
	/**
	 * 读取配置
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public <T extends Object> T read(String path,Class<T> clz) {
		
		try {
			config = clz.newInstance();
			
			Properties prop = new Properties();
			prop.load(ConfigTool.class.getResourceAsStream(path));
			
			Set<Object> keySet = prop.keySet();
			
			for (Object key : keySet) {
				set(key.toString(), prop.get(key).toString());
			}
			
			return (T) config;
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 填充数据
	 * @param name
	 * @param value
	 * @throws Exception 
	 * @throws  
	 */
	private void set(String name, String value) throws Exception {
		
		Field field;
		
		try {
			field = config.getClass().getDeclaredField(name);
		} catch (Exception e) {
			Log.info(config.getClass()+" => 忽略配置项：" + name);
			return;
		}
		
		field.setAccessible(true);
		if(field.getName().equals(name)) {
			
			if(field.getType().equals(int.class) || field.getType().equals(Integer.class) )  {
				field.set(config,Integer.parseInt(value));
			} else if(field.getType().equals(long.class) || field.getType().equals(Long.class) )  {
				field.set(config,Long.parseLong(value));
			} else if(field.getType().equals(short.class) || field.getType().equals(Short.class) )  {
				field.set(config,Short.parseShort(value));
			} else if(field.getType().equals(float.class) || field.getType().equals(Float.class) )  {
				field.set(config,Float.parseFloat(value));
			} else if(field.getType().equals(double.class) || field.getType().equals(Double.class) )  {
				field.set(config,Double.parseDouble(value));
			} else if(field.getType().equals(boolean.class) || field.getType().equals(Boolean.class) )  {
				field.set(config,Boolean.parseBoolean(value));
			} else {
				field.set(config,value);
			}
		
		}
	}
	
}
